﻿using System;
using System.Collections.Generic;
using Plugins.Core;
using StockAccessors;
using StockModel;
using Plugins;
using Utils;

namespace StockAnalyst2.Plugins.Engine
{
	internal class PluginActivator
	{
		#region Attributes

		private readonly IDataBaseClient _dbClient;
		private readonly QuotationDataSource _quotationDataSource;
		private readonly ExchangeMarketDataSource _exchangeMarketDataSource;
		private readonly RawStockDataSource _rawStockDataSource;
		private readonly ObservableCollection2<StockGroup> _groups;
		private readonly IOrderExecutor _executor;
		private readonly IStockDataAccessorInformation _accessorInformation;

		#endregion

		#region Public Methods



		public PluginActivator(IDataBaseClient dbClient, QuotationDataSource quotationDataSource, ExchangeMarketDataSource exchangeMarketDataSource, RawStockDataSource rawStockDataSource, ObservableCollection2<StockGroup> groups, IOrderExecutor executor, IStockDataAccessorInformation accessorInformation)
		{
			_quotationDataSource = quotationDataSource;
			_dbClient = dbClient;
			_exchangeMarketDataSource = exchangeMarketDataSource;
			_groups = groups;
			_executor = executor;
			_accessorInformation = accessorInformation;
			_rawStockDataSource = rawStockDataSource;
		}

		public IEnumerable<IStrategyPlugin> InstantiatePlugins(IEnumerable<Type> pluginTypes)
		{
			List<IStrategyPlugin> result = new List<IStrategyPlugin>();

			foreach (Type type in pluginTypes)
			{
				IStrategyPlugin plugin = (IStrategyPlugin)Activator.CreateInstance(type);

				try
				{
					plugin.Initialize(_dbClient, _quotationDataSource, _exchangeMarketDataSource, _rawStockDataSource, _groups, _executor, _accessorInformation);
					result.Add(plugin);
				}
				catch (Exception ex)
				{
					string pluginName = plugin.VisualRepresentation != null ? plugin.VisualRepresentation.MenuText : "Unknown";
					ExceptionLogger.LogException("There was an error instantiating the pluging " + pluginName + ". It won't be available until the error is fixed and the application is restarted.", ex, false);
				}
			}

			return result;
		}

		#endregion
	}
}
